<?php
namespace org\kahikai\database\mysql;

require_once dirname(__FILE__) . '/../UserDao.php';
require_once dirname(__FILE__) . '/KahikaiMysql.php';
require_once dirname(__FILE__) . '/../../domain/User.php';

use org\kahikai\database\UserDao;
use org\kahikai\domain\User;

/**
 * 
 * @author ch4mp
 *
 */
class MysqlUserDao implements UserDao {
	
	/**
	 *
	 * @param string $email the email of seeked user
	 * @return the User with provided email or null
	 */
	public function getByEmail($email) {
		$user = null;
	
		$result = KahikaiMysql::query("SELECT id, last_name, first_name, password, profile, confirmation_code FROM USERS WHERE email='$email'");
		if ($result) {
			if($record = $result->fetch_assoc()) {
				$user = new User($record['id'], $record['last_name'], $record['first_name'], $email, $record['profile'], $record['password'], $record['confirmation_code']);
			}
			$result->close();
		}
	
		return $user;
	}
	
	/**
	 * 
	 * @param string $id a user id
	 * @return the User with provided id or null
	 */
	public function getById($id) {
		$user = null;
	
		$result = KahikaiMysql::query("SELECT last_name, first_name, email, password, profile, confirmation_code FROM USERS WHERE id='$id'");
		if ($record = $result->fetch_assoc()) {
			$user = new User($id, $record['last_name'], $record['first_name'], $record['email'], $record['profile'], $record['password'], $record['confirmation_code']);
		}
		$result->close();
	
		return $user;
	}
	
	/**
	 * @param User $user a user to persist
	 * @return newly created user id or null
	 */
	public function saveUser(User $user) {
		$result = KahikaiMysql::query("INSERT INTO USERS(last_name, first_name, email, password, profile, confirmation_code) VALUES(" . 
				"'" . $user->lastName . "', " . 
				"'" . $user->firstName . "', " . 
				"'" . $user->email . "', " . 
				"'" . $user->password . "', " . 
				"'" . $user->profile . "', " . 
				$user->confirmationNumber . ")");
		if($result) {
			$result = KahikaiMysql::query("SELECT id FROM USERS WHERE email='$user->email'");
			if ($record = $result->fetch_assoc()) {
				KahikaiMysql::commit();
				return $record['id'];
			}
		}
		KahikaiMysql::rollback();
		return null;
	}
	
	/**
	 * @param User $user a user to update
	 * @return true if user was found and updated
	 */
	public function update(User $user) {
		return KahikaiMysql::query("UPDATE USERS SET ".
				"last_name='$user->lastName', " . 
				"first_name='$user->firstName', " . 
				"email='$user->email', " . 
				"password='$user->password', " . 
				"profile='$user->profile', " . 
				"confirmation_code=" . ($user->confirmationNumber == null ? 'NULL' : $user->confirmationNumber) . " WHERE id=$user->id");
	}
}
?>